package com.example.zbh.lessona.sensor;

import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.util.Log;

import com.example.zbh.lessona.R;

/**
 * Created by zbh on 15/12/19.
 */
public class SensorActivity extends Activity {
    private SensorManager manager;
    private Sensor sensor;
    private SensorLightListener listener;
    private SoundPool pool;
    private int soundId;
    private float ac = 0.0f;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sensor);
        pool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
        soundId = pool.load(this, R.raw.fallbackring,1);
        manager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        sensor = manager.getDefaultSensor(Sensor.TYPE_LIGHT);
        listener = new SensorLightListener();
        manager.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_FASTEST);
        if (getAc() ==0.0f){
            pool.play(soundId, 1.0f, 1.0f, 1, -1, 1.0f);
        }else {
            if (pool != null){
                pool.release();
                pool = null;
            }
        }

    }
    private float getAc(){
        return ac;
    }
    private class SensorLightListener implements SensorEventListener{

        @Override
        public void onSensorChanged(SensorEvent event) {
            float lightR = event.values[0];
            ac = lightR;
            Log.d("nanchaodong", "onSensorChanged() called with: " + "event = [" + lightR + "]");


        }
        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        manager.unregisterListener(listener);
        listener = null;
        if (pool != null){
            pool.release();
            pool = null;
        }
    }
}
